<template>
	<view class="content">
		<div v-if="userinfo">
			<view class="info-item">
				<span>ID:</span>
				<view>{{ userinfo.userId }}</view>
			</view>
			<view class="info-item">
				<span>部门:</span>
				<view>{{ deptIdTree(userinfo.deptId) }}</view>
			</view>
			<view class="info-item">
				<span>邮箱:</span>
				<input class="input" v-if="userInfoStarts" type="text" v-model="userinfo.email" />
				<view v-else>{{ userinfo.email }}</view>
			</view>
			<view class="info-item">
				<span>昵称:</span>
				<input class="input" v-if="userInfoStarts" type="text" v-model="userinfo.nickName" />
				<view v-else>{{ userinfo.nickName }}</view>
			</view>
			<view class="info-item">
				<span>姓名:</span>
				<input class="input" v-if="userInfoStarts" type="text" v-model="userinfo.userName" />
				<view v-else>{{ userinfo.userName }}</view>
			</view>
			<view class="info-item">
				<span>手机号:</span>
				<input class="input" v-if="userInfoStarts" type="text" v-model="userinfo.phonenumber" />
				<view v-else>{{ userinfo.phonenumber }}</view>
			</view>
			<view class="info-item">
				<span>性别:</span>
				<view v-if="!userInfoStarts">{{ getSexText(userinfo.sex) }}</view>
				<uni-forms-item v-else style="margin: 0;display: flex;align-items: center;" name="sex">
					<uni-data-checkbox v-model="userinfo.sex" :localdata="sexs" />
				</uni-forms-item>
			</view>
			<view class="info-item">
				<span>签订时间:</span>
				<span
					v-if="!userInfoStarts">{{userinfo.userOtherInfo.contractSigningTime?userinfo.userOtherInfo.contractSigningTime:2023-12-12}}</span>
				<view v-else class="uni-list">
					<view class="uni-list-cell">
						<view class="uni-list-cell-db">
							<picker mode="date" :value="date" :start="startDate" :end="endDate"
								@change="bindTimedataChange">
								<view class="uni-input">{{date}}</view>
							</picker>
						</view>
					</view>
				</view>
			</view>
			<view class="info-item">
				<span>入职时间:</span>
				<span
					v-if="!userInfoStarts">{{userinfo.userOtherInfo.entryTime?userinfo.userOtherInfo.entryTime:2023-12-12}}</span>
				<view v-else class="uni-list">
					<view class="uni-list-cell">
						<view class="uni-list-cell-db">
							<picker mode="date" :value="dates" :start="startDate" :end="endDate"
								@change="bindTimedatasChange">
								<view class="uni-input">{{dates}}</view>
							</picker>
						</view>
					</view>
				</view>
			</view>
			<view class="info-item">
				<span>学历:</span>
				<span v-if="!userInfoStarts"> {{ getSexTexts(userinfo.userOtherInfo.education)}}</span>
				<uni-forms-item v-else style="margin: 0;display: flex;align-items: center;" name="sexeducation">
					<uni-data-checkbox :map="{ value: 'dictValue', text: 'dictLabel' }"
						v-model="userinfo.userOtherInfo.education" :localdata="sexeducation" />
				</uni-forms-item>

			</view>
			<view class="info-item">
				<span>毕业院校:</span>
				<input class="input" v-if="userInfoStarts" type="text"
					v-model="userinfo.userOtherInfo.graduationInstitution" />
				<view v-else>{{ userinfo.userOtherInfo.graduationInstitution }} </view>
			</view>
			<view class="info-item">
				<span>身份证号:</span>
				<input class="input" v-if="userInfoStarts" type="text" v-model="userinfo.userOtherInfo.idCard" />
				<view v-else>{{ userinfo.userOtherInfo.idCard }} </view>
			</view>
			<view class="info-item">
				<span>身份证地址:</span>
				<input class="input" v-if="userInfoStarts" type="text" v-model="userinfo.userOtherInfo.idCardAddress" />
				<view v-else>{{ userinfo.userOtherInfo.idCardAddress }} </view>
			</view>
			<view class="info-item">
				<span>专业:</span>
				<input class="input" v-if="userInfoStarts" type="text" v-model="userinfo.userOtherInfo.speciality" />
				<view v-else>{{ userinfo.userOtherInfo.speciality }} </view>
			</view>
			<view class="info-item">
				<span>银行卡号:</span>
				<input class="input" v-if="userInfoStarts" type="text" v-model="userinfo.userOtherInfo.bankCard" />
				<view v-else>{{ userinfo.userOtherInfo.bankCard }} </view>
			</view>
			<view class="info-item">
				<span>银行卡名称:</span>
				<input class="input" v-if="userInfoStarts" type="text" v-model="userinfo.userOtherInfo.bankName" />
				<view v-else>{{ userinfo.userOtherInfo.bankName }} </view>
			</view>
			<view class="info-item">
				<span>开户行地址:</span>
				<input class="input" v-if="userInfoStarts" type="text" v-model="userinfo.userOtherInfo.bankAddress" />
				<view v-else>{{ userinfo.userOtherInfo.bankAddress }} </view>
			</view>
			<view class="info-item">
				<span>住址:</span>
				<input class="input" v-if="userInfoStarts" type="text" v-model="userinfo.userOtherInfo.address" />
				<view v-else>{{ userinfo.userOtherInfo.address }} </view>
			</view>
			<view class="info-item">
				<span>身份证正面:</span>
				<view class="uploadimg">
					<img :src="imgurl(userinfo.userOtherInfo.idCardZ?userinfo.userOtherInfo.idCardZ:'')"
						:alt="userinfo.userOtherInfo.idCardZ?' 加载失败':'未上传'">
					<button v-if="userInfoStarts" style="margin: 0;" class="mini-btn" type="primary" size="mini"
						@click="uploadidCardZ">上传正面</button>
				</view>
			</view>
			<view class="info-item">
				<span>身份证正面:</span>
				<view class="uploadimg">
					<img :src="imgurl(userinfo.userOtherInfo.idCardF?userinfo.userOtherInfo.idCardF:'')"
						:alt="userinfo.userOtherInfo.idCardF?'加载失败':'未上传'">
					<button v-if="userInfoStarts" style="margin: 0;" class="mini-btn" type="primary" size="mini"
						@click="uploadidCardF">上传正面</button>
				</view>
			</view>

		</div>
		<div v-if="userinfo" class="Buttarr">
			<button v-if="userInfoStarts" style="margin: 0;" class="mini-btn" type="primary" size="mini"
				@click="cancelEdit">取消</button>
			<button v-if="!userInfoStarts" style="margin: 0;" class="mini-btn" type="primary" size="mini"
				@click="startEdit">修改</button>
			<button style="margin: 0;" class="mini-btn" type="primary" size="mini" @click="saveChanges">保存</button>
			<button style="margin: 0;" class="mini-btn" type="primary" size="mini" @click="deleteUser">删除</button>
		</div>

	</view>
</template>

<script>
	import {
		getUser,
		deptTreeSelect,
		updateUser,
		getsexeducation
	} from '@/api/work/user.js'

	import
	upload
	from '@/api/components/upload.js'

	import {
		baseUrl
	} from '@/config.js'

	export default {
		data() {
			return {
				date: '',
				dates: '',
				userInfoStarts: false,
				deptTree: [],
				userId: null,
				userinfo: null,
				userOtherInfo: null,
				sexs: [{
					text: '男',
					value: "0"
				}, {
					text: '女',
					value: "1"
				}],
				sexeducation: []
			}
		},

		computed: {
			startDate() {
				return this.getDate('start');
			},
			endDate() {
				return this.getDate('end');
			}
		},
		onLoad(query) {
			this.userId = query.userId;
		},
		onShow() {
			this.getlist();

		},
		methods: {
			imgurl(url) {
				return `${baseUrl}${url}`
			},

			uploadidCardZ() {

				uni.chooseImage({
					count: 1,
					sizeType: ['original'],
					sourceType: ['album', 'camera'],
					success: (chooseRes) => {
						const tempFilePaths = chooseRes.tempFilePaths;
						const filePath = tempFilePaths[0];

						upload({
							url: `${baseUrl}/common/upload`,
							filePath: filePath,
							name: 'file',
						}).then(data => {
							if (data.code == 200) {
								this.userinfo.userOtherInfo.idCardZ = `${data.fileName}`
								this.$modal.showToast('操作成功')
							} else {
								this.$modal.showToast('操作失败')
							}

						}).catch(error => {
							this.$modal.showToast('操作失败')
						});
					},
					fail: (error) => {
						console.error("选择图片失败", error);
					}
				});
			},
			uploadidCardF() {

				uni.chooseImage({
					count: 1,
					sizeType: ['original'],
					sourceType: ['album', 'camera'],
					success: (chooseRes) => {
						const tempFilePaths = chooseRes.tempFilePaths;
						const filePath = tempFilePaths[0];

						upload({
							url: `${baseUrl}/common/upload`,
							filePath: filePath,
							name: 'file',
						}).then(data => {
							if (data.code == 200) {
								this.userinfo.userOtherInfo.idCardF = `${data.fileName}`
								this.$modal.showToast('操作成功')
							} else {
								this.$modal.showToast('操作失败')
							}

						}).catch(error => {
							this.$modal.showToast('操作失败')
						});
					},
					fail: (error) => {
						console.error("选择图片失败", error);
					}
				});
			},


			getlist() {
				this.userInfoStarts = false
				this.date = this.getDate({
					format: true
				});
				this.dates = this.getDate({
					format: true
				});

				getUser(this.userId)
					.then(res => {
						if (res.code === 200) {


							getsexeducation('sys_education').then(res => {
								this.sexeducation = res.data
							}).catch(err => console.log(
								err))

							this.userinfo = res.data;
							if (!this.userinfo.userOtherInfo) {
								this.userinfo.userOtherInfo = {
									contractSigningTime: '',
									entryTime: '',
									education: '',
									graduationInstitution: '',
									idCard: '',
									speciality: '',
								};
							} else {
								return;
							}
							return deptTreeSelect();
						} else {
							throw new Error('Failed to fetch user data');
						}
					})
					.then(deptRes => {
						this.deptTree = this.flattenTree(deptRes.data);
						console.log(this.deptTree);
					})
					.catch(error => {
						console.error(error);
					});


			},

			startEdit() {
				this.userInfoStarts = !this.userInfoStarts;
			},
			cancelEdit() {
				this.userInfoStarts = !this.userInfoStarts;
			},
			deptIdTree(deptId) {
				const department = this.deptTree.find(item => item.id === deptId);
				return department ? department.label : '';
			},
			flattenTree(tree, parentLabel = null) {
				let flatList = [];
				tree.forEach(node => {
					let label = node.label;
					if (parentLabel) {
						label = `${parentLabel}-${label}`;
					}
					flatList.push({
						id: node.id,
						label: label
					});
					if (node.children) {
						flatList = flatList.concat(this.flattenTree(node.children, label));
					}
				});
				return flatList;
			},
			getSexText(sexValue) {
				const sex = this.sexs.find(option => option.value === sexValue);
				return sex ? sex.text : '';
			},
			getSexTexts(sexValue) {
				console.log(this.sexeducation)
				const sex = this.sexeducation.find(option => option.dictValue === sexValue);
				console.log(sex)
				return sex ? sex.dictLabel : '';
			},
			getDate(type) {
				const date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();

				if (type && type === 'start') {
					year = year - 60;
				} else if (type && type === 'end') {
					year = year + 2;
				}
				month = month > 9 ? month : '0' + month;
				day = day > 9 ? day : '0' + day;
				return `${year}-${month}-${day}`;
			},

			bindTimedataChange(e) {
				this.date = e.detail.value;
				this.userinfo.userOtherInfo.contractSigningTime = e.detail.value;
				console.log(this.userinfo);
			},
			bindTimedatasChange(e) {
				this.dates = e.detail.value;
				this.userinfo.userOtherInfo.entryTime = e.detail.value;
				console.log(this.userinfo);
			},
			saveChanges() {
				updateUser(this.userinfo).then(res => {
						if (res.code == 200) {
							this.getlist()
							this.$modal.showToast('操作成功')
						}
					})
					.catch(err => {
						this.$modal.showToast('操作失败')
					})
			},
			deleteUser() {
				delUser([this.userinfo.userId]).then(res => {
						if (res.code == 200) {
							this.$modal.showToast('操作成功')
							this.$tab.navigateTo('/pages/work/user/user')
						}
					})
					.catch(err => {
						this.$modal.showToast('操作失败')
					})
			},
		},
	};
</script>

<style lang="scss" scoped>
	.content {
		width: 100%;
		height: 100%;
		padding: 20px;
		font-family: Arial, sans-serif;
		color: #333;
	}

	.uploadimg {
		width: 74%;
		display: flex;
		height: 100%;
		justify-content: space-around;
		align-items: center;

		img {
			width: 100upx;
			height: 100upx;
		}

		.mini-btn {
			height: 60upx;
		}
	}

	.info-item {
		margin-bottom: 10px;
		border: 1px solid #ddd;
		display: flex;
		align-items: center;
		box-sizing: border-box;
		padding: 10px;

		span {
			margin-right: 10upx;
		}

		.input {
			border: 1px solid #ddd;
			box-sizing: border-box;
			padding-left: 10upx;
		}
	}

	.Buttarr {
		display: flex;
		justify-content: space-around;
		align-items: center;
	}
</style>